﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Windows.Controls;
using Caliburn.Micro;
using OI.Async;
using OI.DataModel;
using OI.Events;

namespace OI.ViewModels
{
    [Export(typeof(CategoryViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class CategoryViewModel : Screen
    {
        public string Header { get { return "categories"; } }
        public BindableCollection<OICategory> Items { get; set; }
        public IEventAggregator Events { get; set; }
        public bool ItemsAreNew { get; set; }

        [ImportingConstructor]
        public CategoryViewModel(IEventAggregator events)
		{
            Events = events;
		}

        // when this view loads, async populate categories
        protected override void OnViewLoaded(object view)
        {
            if (Items == null)
            {
                 Coroutine.BeginExecute(LoadCategories());
            }
        }


        public IEnumerator<IResult> LoadCategories()
        {
            Events.Publish(new ShowBusy { Caption = "loading categories..." });

            var cq = new CatalogQuery<OICategory>(Configuration.Jurisdiction.ID);
            yield return cq;

            Items = new BindableCollection<OICategory>(cq.Results);
            Items.Insert(0, new OICategory { Name = "All" });

            ItemsAreNew = true;
            NotifyOfPropertyChange(() => Items);
            ItemsAreNew = false;

            Events.Publish(new HideBusy());
        }


        // make sure 'all' item initially checked
        public void ItemLoaded(OICategory item, RadioButton source)
        {
            if (ItemsAreNew)
            {
                source.IsChecked = (item.ID == 0);
            }
        }


        // called when an item is selected
        public void Select(OICategory item)
        {
            Events.Publish(new ChangeCatalogFilter()
            {
                FilterType = ChangeCatalogFilter.Filter.Category,
                FilterItem = item
            });
        }
    }
}
